package cn.waka.sys.admin.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.waka.sys.admin.dao.MerchantDao;
import cn.waka.sys.admin.object.Merchant;
import cn.waka.sys.admin.object.Page;

@Service
public class MerchantService {


    private MerchantDao merchantDao;

    @Autowired
    public void setMerchantDao(MerchantDao merchantDao) {
        this.merchantDao = merchantDao;
    }

    public Page findPage(Page p, int type) {
        int page = p.getPage();
        int start = (page - 1) * p.getSize();
        int size = p.getSize();
        List<Merchant> list = merchantDao.findPage(type, start, size);
        int count = merchantDao.findTotal(type);
        p.setCount(count);
        p.setData(list);

        int totalPage = 0;
        if (count > 0 && count % p.getSize() > 0) {
            totalPage = (int) Math.floor(count / p.getSize());
            totalPage++;
        } else {
            totalPage = count / p.getSize();
        }
        if (totalPage == 0) {
            totalPage = 1;
        }
        p.setTotalPage(totalPage);

        return p;
    }

    public Merchant findById(int id) {
        Merchant v = merchantDao.getById(id);
        v.setId(id);
        return v;
    }

    public int delById(int id) {
        return merchantDao.del(id);
    }

    public int save(Merchant m) {
        if (m == null) {
            return 0;
        }
        if (m.getId() == 0) {

            return merchantDao.insert(m);
        }

        return merchantDao.update(m);
    }


}
